package com.buba.springcloud.controller;

import com.buba.springcloud.entities.CommonResult;
import com.buba.springcloud.entities.HfCoupon;
import com.buba.springcloud.entities.HfCouponReceiveRecord;
import com.buba.springcloud.service.DiscountService;
import com.buba.springcloud.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * autor：肖宝兴
 */
@RestController
@Slf4j
@RequestMapping("frontdesk/discount")
public class DiscountController {
    @Resource
    private DiscountService discountService;


    /**
     * 优惠卷全查 条件查询
     * @param id
     * @param status
     * @return
     */
    @PostMapping("/finddiscount")
    public CommonResult finddiscount(Integer id , Integer status ){
        List<HfCoupon> hfCoupons = discountService.finddiscount(id ,status);
        return new CommonResult(200,"查询优惠卷成功",hfCoupons);
    }

    /**
     * 查询用户是否领取过优惠券 领取成功后库存减一
     * @param request
     * @param cid
     * @return
     */
    @PostMapping("/GetCoupon")
    public CommonResult GetCoupon(HttpServletRequest request , Integer cid){
        String token = request.getHeader("token");
        Claims claims = JwtUtil.parseJWT(token);
        Integer id = (Integer) claims.get("id");
        HfCouponReceiveRecord hfCouponReceiveRecord = discountService.finddiscountById(id , cid);
        if (hfCouponReceiveRecord != null){
            return new CommonResult(500,"用户领取过此优惠券");
        }else {
            discountService.getCoupon(id , cid);
            HfCoupon hfCoupon = discountService.findCouponById(cid);
            long resid =  hfCoupon.getResidualCount() -1;
            discountService.Inventorydecline(resid , cid);
            return new CommonResult(200,"领取优惠券成功");
        }
    }

    /**
     * 查询当前用户优惠卷列表
     * @param request
     * @return
     */
    @GetMapping("/findCouponByUid")
    public CommonResult findCouponByUid(HttpServletRequest request){
        String token = request.getHeader("token");
        Claims claims = JwtUtil.parseJWT(token);
        Integer id = (Integer) claims.get("id");
        List<HfCoupon> hfCoupons = discountService.findCouponByUid(id);
        return new CommonResult(200,"查询成功",hfCoupons);
    }

}
